import {promisic} from "./util";

class WxUtil{

  static async getCode() {
    const res = await promisic(wx.login)();
    return res.code;
  }
  
  static checkLogin(){
	  const app = WxUtil.getApp();
	  let token = app.globalData.token;
	  if(token){
		  return true;
	  }
	  return false;
  }

  static async checkSession() {
    try {
      await promisic(wx.checkSession)();
    } catch (e) {
      const code = await WxUtil.getCode();
      const app = WxUtil.getApp();
      app.globalData.code = code;
    }

  }

  static async chooseImage(count, sourceType=['album', 'camera']) {
    return await promisic(wx.chooseImage)({
      count,
      sizeType: ['compressed'],
      sourceType
    });
  }

  static async getImageInfo(src) {
    return await promisic(wx.getImageInfo)({
      src
    });
  }

  static async pay(params) {
    return await promisic(wx.requestPayment)(params);
  }

  static async getLocation() {
    try {
      return await promisic(wx.getLocation)();
    } catch (e) {
      WxUtil.showModel('定位失败', '请确认微信定位权限已开启且允许小程序获取位置');
      return {latitude: 23.148004, longitude: 113.248345}
    }
  }


  static uploadFile({url, filePath, formData}, onProgress=(res)=>console.log(res), cancelTask) {
    return new Promise((resolve, reject) => {
      const task = wx.uploadFile({
        url, filePath, formData,
        name: 'file',
        success: (res) => {
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        }
      });
      if(onProgress && typeof onProgress === 'function') {
        task.onProgressUpdate((res) => {
          onProgress(res);
        })
      }
      if(cancelTask && typeof cancelTask === 'function') {
        cancelTask(() => {
          task.abort();
        });
      }
    });
  }

  static async initApp({token, phone, openId}) {
    const app = WxUtil.getApp();
    app.globalData.token = token;
    wx.setStorageSync('token', token);
    app.globalData.openId = openId;
    wx.setStorageSync('openId', openId);
    app.globalData.userInfo.phone = phone;
    wx.setStorageSync('userInfo.phone', phone);
    app.globalData.hasLogin = true;
    await WxUtil.initDefaultMember();
  }



  static getApp() {
    return getApp();
  }

  static logout() {
    const app = WxUtil.getApp();
    app.globalData.token = '';
    wx.setStorageSync('token', '');
    app.globalData.openId = '';
    wx.setStorageSync('openId', '');
    app.globalData.userInfo = {};
    wx.setStorageSync('userInfo.phone', '');
    app.globalData.patientInfo = {};
    wx.setStorageSync('patientInfo',{});
    app.globalData.hasLogin = false;
  }

  static showToast(title='提示内容') {
    wx.showToast({
      icon: 'none',
      title
    })
  }

  static async showModel(title='标题', content='内容') {
    return promisic(wx.showModal)({
      title,
      content
    })
  }
}

export {
  WxUtil
}
